import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author fangkun
 * @create 2022-11-22-11:07
 *
 * 案例说明：电商比价需求
 * 1 同一款产品，同时搜索出同款产品在各大电商的售价;
 * 2 同一款产品，同时搜索出本产品在某一个电商平台下，各个入驻门店的售价是多少
 *
 * 出来结果希望是同款产品的在不同地方的价格清单列表，返回一个List<String>
 */
public class CompletableFutureNetMallDemo {

    static List<NetMall> mallList = Arrays.asList(
            new NetMall("jd"),
            new NetMall("tb"),
            new NetMall("tm"),
            new NetMall("dw"),
            new NetMall("pdd")
    );

    //同步方式
    public static List<String> getPriceByStep(List<NetMall> list,String productName) {
        return list.stream().map(netMall -> String.format(productName + " in %s price is %.2f", netMall.getMallName(),netMall.calcPrice(productName))).collect(Collectors.toList());
    }

    //异步方式
    public static List<String> getPriceByAsycn(List<NetMall> list,String productName) {
        return list.stream().map(netMall -> CompletableFuture.supplyAsync(() -> String.format(productName + " in %s price is %.2f", netMall.getMallName(),netMall.calcPrice(productName)))).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        List<String> list = getPriceByStep(mallList, "java");
        for (String element : list) {
            System.out.println(element);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("-----花费时间为："+ (endTime - startTime)+"毫秒-----");

        System.out.println("----------------------------------------");

        long startTime2 = System.currentTimeMillis();
        List<String> list2 = getPriceByAsycn(mallList, "java");
        for (String element : list2) {
            System.out.println(element);
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("-----花费时间为："+ (endTime2 - startTime2)+"毫秒-----");
    }
}

class NetMall {

    private String mallName;

    public NetMall(String mallName){
        this.mallName = mallName;
    }

    public double calcPrice(String productName){
        //模拟检索时间1s
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }

    public String getMallName() { return mallName; }
}